"""
文件夹下的图片合并成一张,生成plist 查询字典
"""
import os
import sys

import biplist


def init_big_png():
    """
    all in one
    :return:
    """
    root_dir = "new_payload"
    image_dist = dict()
    images = open('my_png', 'wb')
    for _dir, _dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.png') or file.endswith('.jpg'):
                file_path = os.path.join(_dir, file)
                begin_offset = images.tell()
                with open(file_path, 'rb') as img_file:
                    img_bytes = img_file.read()
                    images.write(img_bytes)
                    images.flush()

                end_offset = images.tell()
                if file in image_dist.keys():
                    print("not good")
                    sys.exit()
                image_dist[file] = "%d,%d" % (begin_offset, end_offset)

    biplist.writePlist(image_dist, 'image_dict.plist', binary=False)
    images.close()


def read_big_png():
    """
    export AppIcon20x20@2x.png
    :return:
    """
    big_images = open('my_png', 'rb')
    img_dict = biplist.readPlist('image_dict.plist')
    arr = img_dict.get('AppIcon20x20@2x.png').split(',')
    big_images.seek(int(arr[0]))
    read = big_images.read(int(arr[1]) - int(arr[0]))
    with open('text.png', 'wb') as tmp_file:
        tmp_file.write(read)


if __name__ == '__main__':
    # init_big_png()
    read_big_png()
